<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1"
    element-loading-text="加载中..."
  >
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addData"> 添加预警 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search flex-align-center">
        <el-input
          v-model="name"
          placeholder="区间值搜索"
          class="input-with mr5"
          clearable
          @keyup.enter="getList"
           @clear="getList"
        />
        <div class="filter">
          <el-button type="primary" color="#007cff" class="search_btn" @click="getList">
            <el-icon class="mr5">
              <Search />
            </el-icon>
            搜索
          </el-button>
        </div>
      </div>
    </div>
    <div class="table-list">
      <el-table
        border
        stripe
        resizable
        :data="tableData"
        @selection-change="handleChange"
        ref="tableDom"
        height="100%"
        style="position: absolute"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" fixed="left" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
        />
        <el-table-column show-overflow-tooltip prop="max,min" label="预警名称" min-width="200">
          <template #default="item">
            <span>{{ item.row.min }} ~ {{ item.row.max }}天未处理</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="!scope.row.status">启用</HStatus>
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="color" label="预警颜色" width="100" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="editData(scope.row.id)">编辑</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  预警弹窗 -->
    <HModal class="add-dialog" v-model="addDialog" :width="500">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="dialogLoading" element-loading-text="加载中...">
        <div class="form-text">
          <el-form
            label-width="120"
            ref="formRef"
            :rules="rules"
            :model="form"
            @validate="handleFormValidate"
          >
            <!-- 结果 -->
            <el-form-item label="预警名称">
              <span style="white-space: nowrap"
                >{{ form.min }}&nbsp;~&nbsp;{{ form.max }}天未处理</span
              >
            </el-form-item>

            <!-- 预警区间(开始) -->
            <el-form-item label="预警区间(开始)" prop="min" :style="getFormItemStyle['min']">
              <el-input v-model="form.min" clearable maxlength="6" placeholder="最小值" />
            </el-form-item>

            <!-- 预警区间(结束) -->
            <el-form-item label="预警区间(结束)" :style="getFormItemStyle['max']" prop="max">
              <el-input v-model="form.max" clearable maxlength="6" placeholder="最大值" />
            </el-form-item>

            <!-- 预警状态 -->
            <el-form-item label="预警状态" class="form_radio_item" style="margin-bottom: 12px">
              <el-radio-group v-model="form.status">
                <el-radio :value="false">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 预警颜色 -->
            <el-form-item label="预警颜色" class="form-item">
              <el-color-picker v-model="form.color" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          type="error"
          is-modal
          v-show="dialogTitle == '编辑预警'"
          @click="changeStatus(4)"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive, markRaw } from 'vue'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { warnSave, warnGetList, warnGetDetail, warnDisable, warnDelete } from '@/api/basic'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, getFormItemStyle } = useFormValidateService([
    {
      name: 'min',
      isSelect: false,
    },
    {
      name: 'max',
      isSelect: false,
      errMarginBottom: 24,
    },
  ])

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    resetFormValidateResult()
  }

  const loading = ref(false)
  const addDialog = ref(false)
  const name = ref('') // 关键词

  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const formRef = ref<FormInstance>() // 表单元素
  const dialogTitle = ref('')
  const dialogLoading = ref(false)

  // 表单数据
  const form = reactive({
    color: '#f56c6c',
    id: null,
    max: 4,
    min: 2,
    status: false,
    weight: 1,
  })

  // 验证规则
  const rules = reactive({
    min: [
      { required: true, message: '请输入最小值', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    max: [
      { required: true, message: '请输入最大值', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    weight: [
      { required: true, message: '请输入预警权重', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取分页数据
  const getPageData = () => {
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await warnGetList(getPageData()).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 添加预警
  const addData = () => {
    dialogTitle.value = '添加预警'
    addDialog.value = true
    form.color = '#f56c6c'
    form.id = null
    form.max = 4
    form.min = 2
    form.status = false
    form.weight = 1
  }

  // 编辑预警
  const editData = async (id) => {
    addDialog.value = true
    dialogLoading.value = true
    dialogTitle.value = '编辑预警'
    await warnGetDetail(id).then((res) => {
      form.color = res.data.data.row.color
      form.id = res.data.data.row.id
      form.max = res.data.data.row.max
      form.min = res.data.data.row.min
      form.status = res.data.data.row.status
      form.weight = res.data.data.row.weight
    })
    dialogLoading.value = false
  }

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        addDialog.value = false
        dialogLoading.value = false
        getList()
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        dialogLoading.value = false
        return
      }
    })
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (form.max < form.min) {
          ElMessage({
            message: '最大值不能小于最小值',
            type: 'warning',
            duration: 2000,
          })
          return
        }
        saveDataMethod(warnSave, form)
      }
    })
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的预警`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的预警?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', warnDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', warnDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', warnDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', warnDelete, [form.id], 3, addDialog)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
